<template>
  <el-drawer
    v-loading="drawerLoading"
    :visible.sync="dialogVisible"
    append-to-body
    show-close
    :title="info.name"
    :direction="direction"
    size="70%"
    style="min-width: 1036px"
    :before-close="handleClose">

    <div class="app-container">
      <div class="header">
        <el-row :gutter="20" style="padding: 30px 20px 5px;">
          <el-col :span="14">
            <div style="display: flex">
              <div style="margin-right: 15px;">
                <img
                  src=""
                  class="t-section__hd">
              </div>
              <div style="line-height:1.15">
                <span class="customer-title">客户</span>
                <br>
                <span class="customer-name">{{info.name}}</span>

                <span class="customer-name">
                  <el-rate
                    v-model="info.attention"
                    :disabled="isWater"
                    @change="setCustomerAttention(info.id,info.attention)"
                    :colors="colors">
                  </el-rate>
                </span>
              </div>
            </div>
          </el-col>
          <el-col :span="10">
            <div style="line-height: 2">
              <template v-if="isMy || isIntention">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="editRow()">编辑</el-button>
              <el-button type="success" size="mini" icon="el-icon-success" @click="changeStatusRow()">更改成交状态</el-button>
              <el-dropdown style="margin-left: 10px" @command="handleCommand">
                <el-button size="mini" icon="el-icon-more"/>
                <el-dropdown-menu slot="dropdown">
                  <template v-if="isMy || isIntention">
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'group')">设置分组</el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'label')">设置标签</el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'intention')">更改意向状态</el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'intention')">更改意向状态</el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'email',info.name,info.email)">新增营销任务</el-dropdown-item>
                  <el-dropdown-item :command="beforeHandleCommand(info.id,'private',0)">移入公海</el-dropdown-item>
                  </template>
                </el-dropdown-menu>
              </el-dropdown>
              </template>
              <template v-if="isWater">
                <el-button size="mini" icon="el-icon-s-fold" @click="privateRow(info.id,1)">认领客户</el-button>
                <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteCustomer(info.id)">删除客户</el-button>
              </template>
            </div>
          </el-col>
        </el-row>
        <el-row style="padding: 8px 20px 15px;" :gutter="20" class="head-form">
          <el-form class="demo-form-inline" label-position="top">
            <el-col :span="8">
              <el-form-item label="成交状态">
                <template v-if="info.dealStatus == 1">
                  <i class="el-icon-success" style="color: #20b559;"></i>&nbsp;已成交
                </template>
                <template v-else>
                  <i class="el-icon-error" style="color: #f95a5a;"></i>&nbsp;未成交
                </template>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="负责人">
                {{info.belongUser ? info.belongUser.trueName : '无'}}
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="更新时间">
                {{info.updatedAt}}
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
      </div>

      <div class="content">
        <el-tabs type="border-card" v-model="activeName" @tab-click="handleTabClick">
          <el-tab-pane label="详细资料" name="info">
            <el-scrollbar
              ref="myScrollbar"
              :wrap-class="{wrapClass: true}"
              class="form-scrollbar scrollbar-back-top"
            >
              <Info :row="info" v-if="infoTemplateState" :is="infoTemplate"/>
            </el-scrollbar>
          </el-tab-pane>
          <el-tab-pane label="跟进记录" name="follow">

            <FollowTemplate :customerId="id" :isShowAction="isMy || isIntention" v-if="followTemplateState" :is="followTemplate" @refresh="getInfo()"/>
          </el-tab-pane>
          <el-tab-pane label="操作记录" name="log">
            <el-scrollbar
              ref="myScrollbar"
              :wrap-class="{wrapClass: true}"
              class="form-scrollbar scrollbar-back-top"
            >
              <Log :id="id" v-if="logTemplateState" :is="logTemplate"/>
            </el-scrollbar>
          </el-tab-pane>
          <template v-if="isMy || isIntention">
            <el-tab-pane label="营销任务" name="email">
              <el-scrollbar
                ref="myScrollbar"
                :wrap-class="{wrapClass: true}"
                class="form-scrollbar scrollbar-back-top"
              >
                <EmailMarketingTaskIndex :ids="emailIds" v-if="emailMarketingTaskIndexState" :is="emailMarketingTaskIndex"/>
              </el-scrollbar>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>
    </div>
    <Edit :id="id" :show.sync="showState" @closeAction="getInfo" :origin="1"/>
    <ChangeDealStatus :id="id" :show.sync="showChangeDealStatusState" @closeAction="getInfo"/>
    <Group :id="id" :show.sync="showGroupState" @closeAction="getInfo"/>
    <Intention :id="id" :show.sync="showIntentionState" @closeAction="getInfo"/>
    <Label :id="id" :show.sync="showLabelState" @closeAction="getInfo"/>
    <EmailAdd :emailsTemp="emailData" :show.sync="showBaseFormState" @closeAction="getInfo"/>
  </el-drawer>
</template>

<script>
const Log = resolve => require(['@/views/customer/common/log'], resolve)
const Info = resolve => require(['@/views/customer/common/info'], resolve)
const FollowTemplate = resolve => require(['@/views/customer/common/follow'], resolve)
const EmailMarketingTaskIndex = resolve => require(['@/views/email/emailMarketingTask/index'], resolve)
import ChangeDealStatus from '@/views/customer/common/changeDealStatus'
import Group from '@/views/customer/common/group';
import Label from '@/views/customer/common/label';
import Intention from '@/views/customer/common/intention';
import Edit from './edit'
import {deleteCustomer, getCustomer, setAttention, SetIsPrivate} from "@/api/customer";
import EmailAdd from "@/views/customer/index/emailAdd";

export default {
  name: "Drawer",
  components: {Info, Log, Edit, ChangeDealStatus,Group,Label,Intention,EmailAdd},
  props: {
    show: {
      type: Boolean,
      default: false
    },
    id: {
      type: [Number, String],
      default: ''
    },
    closeAction: {
      type: String,
      default: ''
    },
    action: {
      type: [Number, String],
      default: ''
    },
  },
  created() {
    this.initAction()
  },
  data() {
    return {
      isMy: false,
      isIntention: false,
      isWater: false,
      emailIds:[],
      emailData:[],
      showBaseFormState:false,
      dialogVisible: this.show,
      showState: false,
      showIntentionState: false,
      showGroupState: false,
      showLabelState: false,
      showChangeDealStatusState: false,
      direction: 'rtl',
      colors: ['#99A9BF', '#F7BA2A', '#FF9900'],
      attention: 5,
      drawerLoading: true,
      info: {
        name: '',
        attention: 0,
        dealStatus: 0,
      },
      activeName: 'info',
      infoTemplate: '',
      infoTemplateState: false,
      logTemplate: '',
      logTemplateState: false,
      followTemplate: '',
      followTemplateState: false,
      emailMarketingTaskIndex: '',
      emailMarketingTaskIndexState: false,
    };
  },
  methods: {
    initAction(){
      //初始化
      this.isMy = false;
      this.isIntention = false;
      this.isWater = false;

      if (this.action == 1) {
        this.isMy = true;
      }//我的客户
      if (this.action == 2) {
        this.isIntention = true;
      }//意向客户
      if (this.action == 3) {
        this.isWater = true;
      }//
    },
    async getInfo() {
      this.showState = false
      this.showChangeDealStatusState = false
      this.showIntentionState = false
      this.showGroupState = false
      this.showLabelState = false
      this.drawerLoading = true
      await getCustomer(this.id).then((res) => {
        this.info = res.data
        setTimeout(() => {
          this.drawerLoading = false
        }, 0.5 * 1000)
      }).catch(() => {
        setTimeout(() => {
          this.drawerLoading = false
        }, 0.5 * 1000)
      })
    },
    handleClose(done) {
      this.$emit('closeAction')
    },
    setCustomerAttention(id, val) {
      this.$confirm('确认要修改该客户的关注度吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.drawerLoading = true
        let data = {id: id, attention: val}
        await setAttention(data).then((res) => {
          this.$notify({
            title: '成功',
            message: '更新成功',
            type: 'success',
            duration: 2000
          })
          this.getInfo()
        })
      }).catch(() => {
        this.getInfo()
      })
    },
    editRow() {
      this.showState = true;
    },
    changeStatusRow() {
      this.showChangeDealStatusState = true;
    },
    checkTab(name) {
      switch (name) {
        case 'info' :
          this.infoTemplateState = false
          this.infoTemplate = Info
          this.$nextTick(() => {
            this.infoTemplateState = true
          })
          break;
        case 'log' :
          this.logTemplateState = false
          this.logTemplate = Log
          this.$nextTick(() => {
            this.logTemplateState = true
          })
          break;
        case 'follow' :
          this.followTemplateState = false
          this.followTemplate = FollowTemplate
          this.$nextTick(() => {
            this.followTemplateState = true
          })
          break;
        case 'email' :
          this.emailIds = [];
          this.emailIds.push(this.info.id)
          this.emailMarketingTaskIndexState = false
          this.emailMarketingTaskIndex = EmailMarketingTaskIndex
          this.$nextTick(() => {
            this.emailMarketingTaskIndexState = true
          })
          break;
      }
    },
    handleTabClick(tab, event) {
      this.checkTab(tab.name)
    },
    beforeHandleCommand(scope, command,val1 = 0,val2 = null) {
      return {
        'scope': scope,
        'command': command,
        'val': val1,
        'val2': val2,
      }
    },
    handleCommand(command) {
      switch (command.command) {
        case 'group':
          this.groupRow(command.scope)
          break;
        case 'label':
          this.labelRow(command.scope)
          break;
        case 'intention':
          this.intentionRow(command.scope)
          break;
        case 'private':
          this.privateRow(command.scope,command.val)
          break;
        case 'email':
          this.emailData = [];
          let data = {
            id:command.scope,
            name:command.val,
            email:command.val2,
          }
          this.emailData.push(data);
          this.showBaseFormState = true;
          break;
      }
    },
    groupRow(id){
      this.showGroupState = true
    },
    labelRow(id){
      this.showLabelState = true
    },
    intentionRow(id){
      this.showIntentionState = true
    },
    privateRow(id,val){
      this.setCustomerIsPrivateRes(val)
    },
    setCustomerIsPrivateRes(val = 0) {
      let msg = '';
      let title = ''
      if (val == 0) {
        title = '移入'
        msg = '确认要将该客户移入公海？';
        if (typeof this.id != 'object') {
          msg = '确认要将客户移入公海？'
        }
      } else {
        title = '认领'
        msg = '确认要认领该客户？';
        if (typeof this.id != 'object') {
          msg = '确认要认领客户？'
        }
      }

      this.$confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {ids: this.id, value: val}

        if (typeof data.ids != 'object') {
          data.ids = [data.ids]
        }
        await SetIsPrivate(data).then((res) => {
          this.$notify({
            title: '成功',
            message: `${title}成功`,
            type: 'success',
            duration: 2000
          })
          this.$emit('closeAction')
        })
      })
    },
    deleteCustomer(id) {
      this.$confirm('确认要删除客户,此操作不可逆', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await deleteCustomer(id).then((res) => {
          this.$notify({
            title: '成功',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.$emit('closeAction')
        })
      }).catch(() => {

      })
    },
  },
  watch: {
    show() {
      this.dialogVisible = this.show
      if (this.show) {
        this.getInfo()
        this.activeName = 'info'
        this.checkTab(this.activeName)
      }
    },
  }
}
</script>

<style scoped>
.head-form /deep/ .el-form-item__label {
  height: 20px;
  font-size: 12px;
  color: #666;
}

.head-form /deep/ .el-form-item {
  margin-bottom: unset;
}

.customer-title {
  color: #999;
  font-size: 12px;
  margin-bottom: 5px
}

.customer-name {
  color: #333;
  font-size: 16px;
  font-weight: 600;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.header {
  position: relative;
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 10px;
}

.form-scrollbar {
  height: calc(100vh - 325px)
}

.form-scrollbar /deep/ .el-timeline {
  margin: 15px 0 0 0;
}
/deep/ .el-drawer__header{
  margin-bottom: unset!important;
}
</style>
